import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;


public class Compute {
	
	private HashMap<Integer,HashSet<Integer>> map = new  HashMap<Integer,HashSet<Integer>>();
	public static void main(String[] args) {
		Compute c = new Compute();
		c.learn();

	}
	
	public void learn(){
		File f = new File("resources/train.csv");
		
		System.out.println("Miele dejte");
		try {
			Scanner in = new Scanner(f);
			String line;
			String[] info;
			int id,ac;
			HashSet<Integer> set;
			in.nextLine();
			while(in.hasNextLine()){
				line = in.nextLine();
				info = line.split(",");
				ac = Integer.parseInt(info[0]);
				if(ac == 1){
					id = Integer.parseInt(info[1]);
					set = map.get(id);
					if(set == null){
						set = new HashSet<Integer>();
					    map.put(id, set);
					}
					set.add(Integer.parseInt(info[3]));
					set.add(Integer.parseInt(info[4]));
				}
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("Done. Zapisuje na dysk...");
		save();
		test();
	}
	
	public void save(){
		File f = new  File("hash.txt");
		try {
			PrintWriter out = new PrintWriter(f);
			
			for(Integer id: map.keySet()){
				out.println(id + ":" + map.get(id));
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("zapisalem!");
		
	}
	
	public void load(){
		
	}
	
	public void test(){
		System.out.println("Testuje...");
		String line = null;
		PrintWriter out = null;
		try {
			Scanner in = new Scanner(new File("resources/train.csv"));
			out = new PrintWriter(new File("wynik.csv"));
			
			int id,resource;
			
			String[] info;
			in.nextLine();
			out.println("id,ACTION");
			int counter = 1;
			while(in.hasNextLine()){
				line = in.nextLine();
				info = line.split(",");
				id = Integer.parseInt(info[0]);
				resource = Integer.parseInt(info[1]);
				if(check(resource,Integer.parseInt(info[3]),Integer.parseInt(info[4]))){
					out.println(counter + ",1");
				}
				else{
					out.println(counter + ",0");
				}
				
				counter++;
				
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch(Throwable e){
			e.printStackTrace();
		}
		out.flush();
		System.out.println("Po testuje... ");
	}
	
	private boolean check(int res,int role1,int role2){
		HashSet set = map.get(res);
		if(set != null){
			if(set.contains(role1) && set.contains(role2))
				return true;
		}
		return false;
	}

}
